/* communication.c */
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#include "communication.h"

static long id;

static int c2s_id;
static int s2c_id;

int communication_init(){
	id = (long)getpid();
		if ((c2s_id = 
		msgget(C2S_KEY, PERM | IPC_CREAT)) < 0) {
		perror("MSG Key");
		exit(-1);
	}
	if ((s2c_id = 
		msgget(S2C_KEY, PERM | IPC_CREAT)) < 0) {
		perror("MSG Key");
		exit(-1);
	}
	return 0;
}

int send_msg(const char *msg){
	int len;
	msg_data_t data_send;
	strcpy(data_send.text, msg);
	data_send.type = id;
	len = strlen(msg);
    
    	msgsnd(c2s_id, &data_send, len + 1, 0);

	return 0;
}

int recv_msg(char * buf, int max){
	msg_data_t data_recv;

	if (msgrcv(s2c_id, (void *)&data_recv, MAX_MSG_LEN, id , 0) == -1) {
		perror("msgrcv failed with error");
		exit(-1);
	}
	strcpy(buf, data_recv.text);
	return 0;
}
